import redisHelper from './redisHelper.js';
import db from './mysqlHelper.js';
import returnData from './response.js';
import moment from 'moment';
import md5 from 'md5';
import logger from './logger.js';
import jsonwebtoken from 'jsonwebtoken';
import response from './response.js';
import config from './configuration.js';

async function getApp(appId) {
    let app = redisHelper.get(appId);
    if (app == null) {
        app = await db.findOne('app_info', { appid: appId });
        if (app != null) {
            redisHelper.set(appId, app);
            return app;
        }
    } else {
        return JSON.parse(app);
    }
}

function ojbectSort(obj) {
    let temp = Object.keys(obj).sort();
    let temp2 = '';
    for (let index = 0; index < temp.length; index++) {
        if (temp[index] != 'sign' && typeof obj[temp[index]] != 'object') temp2 += temp[index] + '=' + obj[temp[index]] + '&';
    }
    return temp2;
}

function sign(app, data) {
    let str = ojbectSort(data);
    str += 'secret=' + app.secret;
    return returnData.success(md5(str));
}

const whiteList = config.whiteList;

async function auth(ctx, next) {
    const url = ctx.url;
    // 登录验证白名单
    let arr = whiteList.filter((x) => url.indexOf(x) > -1);
    if (arr.length > 0) {
        await next();
        return;
    }
    // 登录验证
    let token = ctx.header.token || '';
    if (token == '') {
        ctx.body = response.fail('请先登录');
        return;
    }
    try {
        let obj = jsonwebtoken.verify(token, secret);
        ctx.state.oper = obj;
    } catch (err) {
        ctx.body = response.fail('登录已过期,请重新登录');
        return;
    }
    await next();
}

const secret = 'token_secret_key';
/**
 *  生成token
 * @param {*} params
 * @returns
 */
async function createToken(params) {
    let token = await jsonwebtoken.sign(params, secret, {
        expiresIn: '2h',
    });
    return { token, expireTime: moment().add(1, 'h').unix() };
}

function generatePwd(pwd) {
    return md5(pwd);
}

export { auth, createToken, generatePwd };
